﻿#include "clockwidget.h"

ClockWidget::ClockWidget(QWidget *parent) : QWidget(parent)
{
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [this]() {
    update(); // 每次定时器触发时更新绘图
      });
      timer->start(1000); // 每秒更新一次
}

void ClockWidget::paintEvent(QPaintEvent *event)
{
        Q_UNUSED(event);

        QPainter painter(this);
        painter.setRenderHint(QPainter::Antialiasing);

        // 将绘图原点移动到窗口中心
        int side = qMin(width(), height());
        painter.translate(width() / 2, height() / 2);
        painter.scale(side / 200.0, side / 200.0);

        drawClock(painter);
}

void ClockWidget::drawClock(QPainter &painter)
{

    static const int hourHand[8] = { -2, 0, 2, 0, 2, -40, -2, -40 };
      static const int minuteHand[8] = { -1, 0, 1, 0, 1, -70, -1, -70 };
      static const int secondHand[8] = { -1, 0, 1, 0, 1, -80, -1, -80 };

      QTime time = QTime::currentTime();

      painter.setPen(Qt::NoPen);

      // 绘制时针
      painter.setBrush(Qt::red);
      painter.save();
      painter.rotate(30.0 * (time.hour() + time.minute() / 60.0));
      painter.drawConvexPolygon(QPolygon(4, hourHand));
      painter.restore();

      // 绘制分针
      painter.setBrush(Qt::green);
      painter.save();
      painter.rotate(6.0 * (time.minute() + time.second() / 60.0));
      painter.drawConvexPolygon(QPolygon(4, minuteHand));
      painter.restore();

      // 绘制秒针
      painter.setBrush(Qt::blue);
      painter.save();
      painter.rotate(6.0 * time.second());
      painter.drawConvexPolygon(QPolygon(4, secondHand));
      painter.restore();

      // 绘制表盘
      painter.setPen(Qt::black);
      for (int i = 0; i < 60; ++i) {
          if ((i % 5) == 0)
              painter.drawLine(88, 0, 96, 0);
          else
              painter.drawLine(92, 0, 96, 0);
          painter.rotate(6.0);
      }

      // 绘制数字 1 到 12
      painter.setPen(Qt::black);
      painter.setFont(QFont("Arial", 12));
      for (int i = 1; i <= 12; ++i) {
          painter.save();
          painter.rotate(30.0 * i);
          painter.translate(0, -80);
          painter.rotate(-30.0 * i);
          painter.drawText(QRect(-10, -10, 20, 20), Qt::AlignCenter, QString::number(i));
          painter.restore();
      }
}

void ClockWidget::drawHand(QPainter &painter, qreal angle, int length)
{
    painter.save();
    painter.rotate(angle);
    painter.drawLine(0, 0, 0, -length);
    painter.restore();
}


